package com.cherry.androidcode.recyclerView

import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.BaseProviderMultiAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder

/**
 * @author DongMS
 * @since 2019/9/4
 */
abstract class AbsPinnedHeaderListAdapter<T, VH : QuickViewHolder>(data: MutableList<T>?) : BaseProviderMultiAdapter<T>(data) {

    init {
        addItemProvider(pinnedHeaderProvider())
        addItemProvider(pinnedDataProvider())
    }


    override fun getItemType(data: List<T>, position: Int): Int {
        return when {
            isHeaderTypeCondition(data[position]) -> TYPE_HEADER
            isDataTypeCondition(data[position]) -> TYPE_DATA
            else -> 0
        }
    }


    abstract fun pinnedHeaderProvider(): AbsPinnedHeaderProvider<T, VH>

    abstract fun pinnedDataProvider(): AbsPinnedDataProvider<T, VH>

    abstract fun isHeaderTypeCondition(t: T): Boolean

    abstract fun isDataTypeCondition(t: T): Boolean

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        // 如果是网格布局，这里处理标签的布局占满一行
        val layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager) {
            val oldSizeLookup = layoutManager.spanSizeLookup
            layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    if (TYPE_HEADER == getItemViewType(position)) {
                        return layoutManager.spanCount
                    }
                    return oldSizeLookup?.getSpanSize(position) ?: 1
                }
            }
        }
    }

    override fun onViewAttachedToWindow(holder: BaseViewHolder) {
        super.onViewAttachedToWindow(holder)
        // 如果是瀑布流布局，这里处理标签的布局占满一行
        val lp = holder.itemView.layoutParams
        if (lp is StaggeredGridLayoutManager.LayoutParams) {
            lp.isFullSpan = getItemViewType(holder.layoutPosition) == TYPE_HEADER
        }
    }

    override fun setOnItemClick(v: View, position: Int) {
        getItemViewType(position).takeIf {
            it == TYPE_DATA
        }?.let {
            super.setOnItemClick(v, position)
        }
    }

    override fun setOnItemLongClick(v: View, position: Int): Boolean {
        if (getItemViewType(position) == TYPE_DATA) {
            return super.setOnItemLongClick(v, position)
        }
        return false
    }

    companion object {
        const val TYPE_HEADER = 1
        const val TYPE_DATA = 2
    }

}